import { useState, useEffect } from 'react';
import { ReactFlowProvider } from 'react-flow-renderer';
import { getIconByType } from './utils/icons';
import Sidebar from './components/Sidebar';
import FlowArea from './components/FlowArea';
import NodePanel from './components/NodePanel';
import ApiDebugPanel from './components/ApiDebugPanel'

const API_BASE = 'http://localhost:8000/api';

function App() {
  // 状态管理
  const [selectedNode, setSelectedNode] = useState(null);
  const [agents, setAgents] = useState([]);
  const [nodes, setNodes] = useState([]);
  const [edges, setEdges] = useState([]);
  const [workflows, setWorkflows] = useState([]);
  const [showSaveWorkflowModal, setShowSaveWorkflowModal] = useState(false);
  const [newWorkflowName, setNewWorkflowName] = useState('');
  const [currentWorkflowId, setCurrentWorkflowId] = useState(null);
  const [saveMode, setSaveMode] = useState('current');
  const [isLoading, setIsLoading] = useState(true);
  const [showApiPanel, setShowApiPanel] = useState(false);
  const [configuringAgent, setConfiguringAgent] = useState(null);

  // 初始化数据
  useEffect(() => {
    const initializeData = async () => {
      try {
        // 获取智能体
        const agentsResponse = await fetch(`${API_BASE}/agents/`);
        if (!agentsResponse.ok) throw new Error('智能体加载失败');
        const agentsData = await agentsResponse.json();
        console.log('agentsData: ', agentsData['results'])
        // 转换数据格式适配前端
        const formattedAgents = agentsData['results'].map(agent => ({
          ...agent,
          icon: getIconByType(agent.agent_type),
        }));
        setAgents(formattedAgents);

        // 获取工作流
        const workflowsResponse = await fetch(`${API_BASE}/workflows/`);
        if (!workflowsResponse.ok) throw new Error('工作流加载失败');
        const workflowsData = await workflowsResponse.json();
        setWorkflows(workflowsData['results']);
        console.log('workflowsData: ', workflowsData['results'])

      } catch (error) {
        console.error('初始化数据失败:', error);
        alert('数据加载失败，请检查后端服务');
      } finally {
        setIsLoading(false);
      }
    };

    initializeData();
  }, []);

  useEffect(() => {
    if (saveMode === 'current' && currentWorkflowId) {
      const currentWorkflow = workflows.find(w => w.id === currentWorkflowId);
      setNewWorkflowName(currentWorkflow ? currentWorkflow.name : '');
    } else {
      setNewWorkflowName('');
    }
  }, [saveMode, currentWorkflowId, workflows]);


  // 创建新智能体
  const handleCreateAgent = async (newAgent) => {
    console.log('newAgent: ', newAgent);
    try {
      const response = await fetch(`${API_BASE}/agents/`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(newAgent)
      });

      if (!response.ok) throw new Error('创建失败');
      const createdAgent = await response.json();
      console.log('createdAgent: ', createdAgent);

      setAgents(prev => [...prev, {
        ...createdAgent,
        icon: getIconByType(newAgent.agent_type)
      }]);
    } catch (error) {
      console.error('创建智能体失败:', error);
      alert('创建失败，请检查输入');
    }
  };

  // 更新智能体
  const handleUpdateAgent = async (agentId, updatedAgent) => {
    console.log('updatedAgent: ', agentId, updatedAgent);
    try {
      const response = await fetch(`${API_BASE}/agents/${agentId}/`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ...configuringAgent,
          config: updatedAgent
        })
      });

      if (!response.ok) throw new Error('更新失败');
      await response.json();

      setAgents(prev => prev.map(agent => 
        agent.id === agentId ? {
          ...agent,
          config: updatedAgent
        } : agent
      ));
      setConfiguringAgent(null);
    } catch (error) {
      console.error('更新智能体失败:', error);
      alert('更新失败，请检查输入');
    }
  };

  // 更新节点数据
  const handleNodeUpdate = (nodeId, updatedData) => {
    console.log('handleNodeUpdate: ', nodeId, updatedData);
    setNodes(nds => nds.map(n => {
      if (n.id === nodeId) {
        const updatedNode = { 
          ...n, 
          data: { 
            ...n.data,
            ...updatedData,
            onChange: n.data?.onChange,
            onTypeChange: n.data?.onTypeChange,
            onConfigChange: n.data?.onConfigChange
          } 
        };
        if (selectedNode?.id === nodeId) setSelectedNode(updatedNode);
        return updatedNode;
      }
      return n;
    }));
  };

  // 保存工作流
  const handleSaveWorkflow = async (name, mode) => {
    const sanitizedNodes = nodes.map(n => {
      const sanitizedData = {...n.data};
      delete sanitizedData.onChange;
      delete sanitizedData.onTypeChange;
      delete sanitizedData.onConfigChange;
      return {...n, data: sanitizedData, selected: false};
    });

    const sanitizedEdges = edges.map(e => ({...e, selected: false}));

    const workflowData = {
      name,
      nodes: sanitizedNodes,
      edges: sanitizedEdges
    };

    try {
      let response;
      if (mode === 'current' && currentWorkflowId) {
        response = await fetch(`${API_BASE}/workflows/${currentWorkflowId}/`, {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(workflowData)
        });
      } else {
        response = await fetch(`${API_BASE}/workflows/`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(workflowData)
        });
      }

      if (!response.ok) throw new Error('保存失败');
      const savedWorkflow = await response.json();
      setCurrentWorkflowId(savedWorkflow.id)

      // 刷新工作流列表
      const workflowsResponse = await fetch(`${API_BASE}/workflows/`);
      const workflowsData = await workflowsResponse.json();
      setWorkflows(workflowsData['results']);

      // if (mode !== 'current') {
      //   setCurrentWorkflowId(savedWorkflow.id);
      // }
    } catch (error) {
      console.error('保存工作流失败:', error);
      alert('保存失败，请检查网络');
    }
  };

  // 加载工作流
  const loadWorkflow = async (workflow) => {
    try {
      const response = await fetch(`${API_BASE}/workflows/${workflow.id}/`);
      if (!response.ok) throw new Error('加载失败');
      const workflowData = await response.json();

      const nodeIdMap = {};
      const timestamp = Date.now();

      const newNodes = workflowData.nodes.map(node => {
        // const newId = `${timestamp}-${node.id}`;
        const newId = `${node.id}`;
        nodeIdMap[node.id] = newId;
        
        const baseNode = {
          ...node,
          id: newId,
          position: { ...node.position }
        };

        if (node.type === 'inputNode') {
          return {
            ...baseNode,
            data: {
              ...node.data,
              onChange: (value) => handleNodeUpdate(newId, { content: value }),
              onTypeChange: (newType) => {
                let newContent = '';
                if (newType === 'boolean') newContent = 'true';
                if (newType === 'json') newContent = '{}';
                handleNodeUpdate(newId, { inputType: newType, content: newContent })
              }
            }
          };
        }

        if (node.type === 'outputNode') {
          return {
            ...baseNode,
            data: {
              ...node.data,
              onVariableChange: (value) => {
                setNodes(nds => nds.map(node => 
                  node.id === newId
                    ? {...node, data: {...node.data, selectedVariable: value}} 
                    : node
                ));
              }
            }
          };
        }

        if (node.type === 'agentNode') {
          return {
            ...baseNode,
            data: {
              ...node.data,
              onConfigChange: (key, value) => handleNodeUpdate(newId, { [key]: value })
            }
          };
        }

        return baseNode;
      });

      const newEdges = workflowData.edges.map(edge => ({
        ...edge,
        id: `edge-${timestamp}-${edge.id}`,
        source: nodeIdMap[edge.source],
        target: nodeIdMap[edge.target]
      }));

      setNodes(newNodes);
      setEdges(newEdges);
      setSelectedNode(null);
      setCurrentWorkflowId(workflowData.id);
    } catch (error) {
      console.error('加载工作流失败:', error);
      alert('加载失败，请重试');
    }
  };

  // 删除智能体
  const handleDeleteAgent = async (agentId) => {
    console.log('handleDeleteAgent: ', agentId)
    if (!window.confirm('确定要删除这个智能体吗？')) return;

    try {
      const response = await fetch(`${API_BASE}/agents/${agentId}/`, {
        method: 'DELETE'
      });

      if (!response.ok) throw new Error('删除失败');
      setAgents(prev => prev.filter(a => a.id !== agentId));
    } catch (error) {
      console.error('删除智能体失败:', error);
      alert('删除失败，请重试');
    }
  };

  // 删除工作流
  const handleDeleteWorkflow = async (workflowId) => {
    if (!window.confirm('确定要删除这个工作流吗？')) return;

    try {
      const response = await fetch(`${API_BASE}/workflows/${workflowId}/`, {
        method: 'DELETE'
      });

      if (!response.ok) throw new Error('删除失败');
      setWorkflows(prev => prev.filter(w => w.id !== workflowId));
      
      if (workflowId === currentWorkflowId) {
        setNodes([]);
        setEdges([]);
        setCurrentWorkflowId(null);
      }
    } catch (error) {
      console.error('删除工作流失败:', error);
      alert('删除失败，请重试');
    }
  };

  if (isLoading) {
    return (
      <div className="w-screen h-screen flex items-center justify-center">
        <div className="text-2xl text-gray-600 animate-pulse">
          数据加载中...
        </div>
      </div>
    );
  }

  const executeWorkflow = async (workflowId, inputData) => {
    try {
      const response = await fetch(`${API_BASE}/workflows/${workflowId}/execute-sync/`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(inputData),
      });
  
      if (!response.ok) throw new Error('执行失败');
      return await response.json();
    } catch (error) {
      console.error('执行失败:', error);
      throw error;
    }
  };

  return (
    <div className="w-screen h-screen overflow-hidden flex">
      <ReactFlowProvider>
        <Sidebar 
          agents={agents}
          workflows={workflows}
          onLoadWorkflow={loadWorkflow}
          onDeleteAgent={handleDeleteAgent}
          onDeleteWorkflow={handleDeleteWorkflow}
          onConfigureAgent={(agent) => {
            setConfiguringAgent(agent);
            setSelectedNode(null); // 新增：关闭节点配置
          }}
        />
        
        <FlowArea
          agents={agents}
          workflows={workflows}
          nodes={nodes}
          setNodes={setNodes}
          edges={edges}
          setEdges={setEdges}
          onSaveWorkflow={() => setShowSaveWorkflowModal(true)}
          handleSaveWorkflow={handleSaveWorkflow}
          onNodeSelect={(node) => {
            setSelectedNode(node);
            setConfiguringAgent(null); // 新增：关闭智能体配置
          }}
          onCreateAgent={handleCreateAgent}
          currentWorkflowId={currentWorkflowId} // 传递当前工作流ID
          onShowApiPanel={() => setShowApiPanel(true)} // 新增回调
          executeWorkflow={executeWorkflow}
        />

        {/* 保存工作流模态框 */}
        {showSaveWorkflowModal && (
          <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
            <div className="bg-white p-6 rounded-lg w-96">
              <h3 className="text-lg font-semibold mb-4">保存工作流</h3>
              
              {currentWorkflowId && (
                <div className="mb-4 space-y-2">
                  <label className="flex items-center gap-2">
                    <input
                      type="radio"
                      checked={saveMode === 'current'}
                      onChange={() => setSaveMode('current')}
                    />
                    <span>保存到当前工作流</span>
                  </label>
                  <label className="flex items-center gap-2">
                    <input
                      type="radio"
                      checked={saveMode === 'new'}
                      onChange={() => setSaveMode('new')}
                    />
                    <span>另存为新工作流</span>
                  </label>
                </div>
              )}

              <input
                type="text"
                placeholder="输入工作流名称"
                className="w-full px-3 py-2 mb-4 border rounded focus:ring-2 focus:ring-blue-500"
                value={newWorkflowName}
                onChange={(e) => setNewWorkflowName(e.target.value)}
              />
              
              <div className="flex justify-end gap-2">
                <button
                  className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded"
                  onClick={() => {
                    setShowSaveWorkflowModal(false);
                    setNewWorkflowName('');
                  }}
                >
                  取消
                </button>
                <button
                  className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50"
                  disabled={!newWorkflowName.trim()}
                  onClick={() => {
                    handleSaveWorkflow(newWorkflowName.trim(), saveMode);
                    setShowSaveWorkflowModal(false);
                    setNewWorkflowName('');
                  }}
                >
                  {saveMode === 'current' ? '保存更改' : '另存为'}
                </button>
              </div>
            </div>
          </div>
        )}

        {showApiPanel && (
          <ApiDebugPanel 
            workflows={workflows}
            workflowId={currentWorkflowId}
            nodes={nodes}
            onClose={() => setShowApiPanel(false)}
            onSaveWorkflow={handleSaveWorkflow}
          />
        )}

        {configuringAgent ? (
          <NodePanel
            node={{
              id: configuringAgent.id,
              type: 'agentConfig',
              data: {
                ...configuringAgent,
              }
            }}
            onSave={handleUpdateAgent}
            onClose={() => setConfiguringAgent(null)}
          />
          ) :
          (
            selectedNode && <NodePanel
            node={
              {
                id: selectedNode.id,
                type: selectedNode.type,
                data: {
                  config: selectedNode.data
                }
              }
            }
            onSave={handleNodeUpdate}
            onClose={() => setSelectedNode(null)}
           />
        )}

      </ReactFlowProvider>
    </div>
  );
}

export default App;
